using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace ChessKit.Common
{
  [DebuggerStepThrough]
  public sealed class DicCache<TKey, TValue> : Dictionary<TKey, TValue>
  {
    private readonly Func<TKey, TValue> _converter;

    public DicCache(Func<TKey, TValue> converter = null)
    {
      _converter = converter;
    }

    public TValue Get(TKey key)
    {
      if (_converter == null)
        throw new InvalidOperationException(
          "You can only use overloaded versions of Get with converter");

      TValue res;
      if (!TryGetValue(key, out res))
        Add(key, res = _converter(key));

      return res;
    }

    public TConcreteValue Get<TConcreteValue>(TKey key, Func<TKey, TConcreteValue> converter)
      where TConcreteValue : TValue
    {
      if (converter == null)
        throw new ArgumentNullException("converter");

      TValue res;
      if (!TryGetValue(key, out res))
        Add(key, res = converter(key));

      return (TConcreteValue)res;
    }
  }


}
